<?php
/**
 * Created by PhpStorm.
 * User: Sky
 * Date: 2017/8/1
 * Time: 下午7:10
 */

namespace app\models;


use app\librarys\DbCacheUtility;
use app\librarys\getui\GetuiClient;
use app\librarys\getui\GetuiClientMerchant;
use app\librarys\Tools;
use YunLianHui\OAuth2;


class Merchant
{
    const SessionKey = 'session_key_merchant';
    const MerchantTokenCacheKey = 'merchant_token:';
    const MerchantTokenExpiresIn = 60 * 60 * 24 * 7;  // user token 过期时间为7天

    const YLHCODE_KEY = 'ylh_code_key_merchant';
    const YLHCODE_EXPIRESIN = 60 * 5; //ylh code 过期时间为5分钟

    const BIGGROUP = 0.25; //大平台提成比例

    /**
     * 获取当前登录商户(如果为null,则未登录)
     * @return mixed|null
     */
    public static function getCurrentMerchant()
    {
        if (\Yii::$app->session->has(self::SessionKey)) {
            $item = \Yii::$app->session->get(self::SessionKey);
            return $item;
        }

        if (YII_DEBUG) {
            $item = self::getById('40953744-76bb-11e7-84d9-00163e06b8e1'); //调试默认使用40953744-76bb-11e7-84d9-00163e06b8e1 merchant账号
            return $item;
        }
        return null;
    }

    /**
     * 商户登录以后,设置到session中
     * @param $merchant
     */
    public static function setCurrentMerchant($merchant)
    {
        \Yii::$app->session->remove(self::SessionKey);
        \Yii::$app->session->set(self::SessionKey, $merchant);
    }

    /**
     * 商户注册
     * @param $phone
     * @return false|null|string
     */
    public static function register($phone)
    {
        $id = Tools::db_uuid();
        $cmd = \Yii::$app->db->createCommand('insert into t_merchant(id, phone, is_auth) values(:id, :phone, 0);');
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':phone', $phone);
        $result = DbCacheUtility::execute($cmd);
        if ($result > 0) {
            return $id;
        } else {
            return null;
        }
    }

    public static function getYlhCode($phone)
    {
//       $item = self::login($phone);
//       return _
        return self::_setYlhCode($phone);

    }

    public static function login($phone)
    {
        $item = self::getByPhone($phone);
        if ($item != null) {
            $merchantToken = self::_setMerchantToken($item['id']);
            $item['token'] = $merchantToken;
            self::setCurrentMerchant($item);

            $cmd = \Yii::$app->db->createCommand('select t1.`status`,t2.`name` as group_name from t_merchant_group t1 LEFT JOIN t_merchant_group_config t2 on t1.merchant_group_id = t2.id where t1.merchant_id=:id ;');
            $cmd->bindValue(':id', $item['id']);
//        $cmd->bindValue(':phone', $phone);
            $item['status'] = DbCacheUtility::queryOne($cmd);
        }
        return $item;
    }

    private static function _setMerchantToken($merchantId)
    {
        // 设置token之前,先将此userId用户以前所用的token清除,已保证每个用户同时只有一个token有效。
        $merchantIdCacheKey = self::MerchantTokenCacheKey . $merchantId;
        $tokenCacheKey = \Yii::$app->cache->get($merchantIdCacheKey);
        if ($tokenCacheKey != false) {
            \Yii::$app->cache->delete($tokenCacheKey);
        }
        \Yii::$app->cache->delete($merchantIdCacheKey);

        $userToken = Tools::uuid();
        $tokenCacheKey = self::MerchantTokenCacheKey . $userToken;

        \Yii::$app->cache->set($merchantIdCacheKey, $tokenCacheKey, self::MerchantTokenExpiresIn);
        \Yii::$app->cache->set($tokenCacheKey, $merchantId, self::MerchantTokenExpiresIn);
//        echo 'set merchant token is :'.$userToken;
        return $userToken;
    }

    private static function _setYlhCode($phone)
    {
        $ylh_code = Tools::db_uuid();
        \Yii::$app->cache->set($ylh_code, $phone, self::YLHCODE_EXPIRESIN);
        return $ylh_code;
    }

    public static function getTokenByYlhCode($ylh_code)
    {
        $phone = \Yii::$app->cache->get($ylh_code);
        return self::login($phone);
    }

    public static function authMerchantToken($merchantToken)
    {
        $tokenCacheKey = self::MerchantTokenCacheKey . $merchantToken;
        $merchantId = \Yii::$app->cache->get($tokenCacheKey);
        if ($merchantId == false) {
            return null;
        }

        $merchantIdCacheKey = self::MerchantTokenCacheKey . $merchantId;
        \Yii::$app->cache->set($merchantIdCacheKey, $tokenCacheKey, self::MerchantTokenExpiresIn);
        \Yii::$app->cache->set($tokenCacheKey, $merchantId, self::MerchantTokenExpiresIn);

        return $merchantId;
    }

    public static function logout()
    {
        self::setCurrentMerchant(null);
    }

    public static function getById($id)
    {
        $cmd = \Yii::$app->db->createCommand('select * from t_merchant where id=:id');
        $cmd->bindValue(':id', $id);
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    public static function getByPhone($phone)
    {
        $cmd = \Yii::$app->db->createCommand('select id,gravatar,`name`,tel,province,city,county,address,is_auth from t_merchant where phone=:phone');
        $cmd->bindValue(':phone', $phone);
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    /**
     * 通过商户id获取商户详细信息
     * @param $id 商户id
     */
    public static function getAuthById($id)
    {
        $cmd = \Yii::$app->db->createCommand('select * from t_merchant_detail where merchant_id=:id');
        $cmd->bindValue(':id', $id);
        //  var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    // region 商户管理
    public static function getCount()
    {
        $cmd = \Yii::$app->db->createCommand('select count(1) from t_merchant');
        $count = DbCacheUtility::queryScalar($cmd);
        return $count;
    }

    public static function getList($page, $pageSize = 20)
    {
        $cmd = \Yii::$app->db->createCommand('select * from t_merchant where is_deleted=0 ORDER BY create_datetime DESC LIMIT :offset , :limit');
        $cmd->bindValue(':offset', $page * $pageSize);
        $cmd->bindValue(':limit', $pageSize * 1);
        $items = DbCacheUtility::queryAll($cmd);
        return $items;
    }

    public static function getDetailById($id)
    {
        $cmd = \Yii::$app->db->createCommand('
            select t0.*, t1.registration_no, t1.business_license_scanning_copy, t1.legal_representative_id_front_photo, t1.legal_representative_id_back_photo, t1.legal_representative_id_photo, t1.legal_representative_id_number from t_merchant t0
            LEFT join t_merchant_detail t1 on t1.merchant_id=t0.id
            where id=:id');
        $cmd->bindValue(':id', $id);
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    public static function setEnabled($id, $isEnabled)
    {
        $cmd = \Yii::$app->db->createCommand('update t_merchant set is_enabled=:isEnabled where id=:id');
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':isEnabled', $isEnabled);
        DbCacheUtility::execute($cmd);
    }
    // endregion


    // region 商户认证审核


    /**
     * update商家资料
     * @param $id
     * @param $tel
     * @param $address
     * @param $gravatar
     */
    public static function setMerchant($id, $tel, $address, $gravatar, $name, $url)
    {
        //var_dump('1111');
        $cmd = \Yii::$app->db->createCommand('update t_merchant set address=:address,tel=:tel,`name`=:name,gravatar=:gravatar,url=:url where id=:id');
        //var_dump('222');
        $cmd->bindValue(':id', $id);
        //var_dump('333');
        $cmd->bindValue(':tel', $tel);
        ///var_dump('444');
        $cmd->bindValue(':address', $address);
        //var_dump('555');
        $cmd->bindValue(':gravatar', $gravatar);
        $cmd->bindValue(':name', $name);
        $cmd->bindValue(':url', $url);

//        var_dump('666');
//        var_dump($cmd->rawSql);
        $item = DbCacheUtility::execute($cmd);
        return $item;
    }

    /**
     * 获取某商户所有认证记录信息
     * @param $merchantId
     * @return mixed
     */
    public static function getAuthRecordAllList($merchantId)
    {
        $cmd = \Yii::$app->db->createCommand('select * from t_merchant_auth_record where merchant_id=:merchantId ORDER BY create_datetime DESC');
        $cmd->bindValue(':merchantId', $merchantId);
        $items = DbCacheUtility::queryAll($cmd);
        return $items;
    }

    public static function authSuccess($authId, $authRemark)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $cmd = \Yii::$app->db->createCommand('update t_merchant_auth_record set `status`=1, remark=:remark where id=:id');
            $cmd->bindValue(':id', $authId);
            $cmd->bindValue(':remark', $authRemark);
            DbCacheUtility::execute($cmd);

            $cmd = \Yii::$app->db->createCommand('update t_merchant set is_auth=1 where id=(select merchant_id from t_merchant_auth_record where id=:id)');
            $cmd->bindValue(':id', $authId);
            DbCacheUtility::execute($cmd);

            $transaction->commit();


            $sql = 'select push_id from t_merchant where id=:id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $authId);
            $push_id = DbCacheUtility::queryScalar($cmd);
            GetuiClientMerchant::pushMessageToSingle($push_id, '您的申请已经审核通过，快快登录屏主平台查看详情吧！');

        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    public static function authFailed($authId, $authRemark)
    {
        $cmd = \Yii::$app->db->createCommand('update t_merchant_auth_record set `status`=2, remark=:remark where id=:id');
        $cmd->bindValue(':id', $authId);
        $cmd->bindValue(':remark', $authRemark);
        DbCacheUtility::execute($cmd);
    }
    // endregion

    /**
     * 编辑商户认证资料
     * @param $id
     * @param $name
     * @param $registration_no
     * @param $business_license_scanning_copy
     * @param $legal_representative_id_front_photo
     * @param $legal_representative_id_back_photo
     * @param $legal_representative_id_photo
     * @param $legal_representative_id_number
     * @param $tel
     * @param $province
     * @param $city
     * @param $county
     * @param $address
     * @param $lon
     * @param $lat
     * @return null
     */
    public static function setMerchantData($id, $name, $registration_no, $business_license_scanning_copy, $legal_representative_id_front_photo, $legal_representative_id_back_photo, $legal_representative_id_photo, $legal_representative_id_number, $tel, $province, $city, $county, $address, $lon, $lat)
    {
        $auth_result = false;
        //查询该商户是否已经存在审核资料t_merchant_detail
        $cmd = \Yii::$app->db->createCommand('select count(*) from t_merchant_detail where merchant_id =:id');
        $cmd->bindValue(':id', $id);
        //var_dump($cmd->rawSql);
        $count = DbCacheUtility::queryScalar($cmd);


        $result = 0;
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            //do sql
            $sql = 'update t_merchant set name=:name,tel=:tel,province=:province,city=:city,county=:county,address=:address,lon=:lon,lat=:lat where id=:id';

            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $id);
            $cmd->bindValue(':name', $name);
            $cmd->bindValue(':tel', $tel);
            $cmd->bindValue(':province', $province);
            $cmd->bindValue(':city', $city);
            $cmd->bindValue(':county', $county);
            $cmd->bindValue(':address', $address);
            $cmd->bindValue(':lon', $lon);
            $cmd->bindValue(':lat', $lat);

            $result = DbCacheUtility::execute($cmd);
//            var_dump($count);
            if ($count > 0) {
                $sql = 'update t_merchant_detail set registration_no=:registration_no,business_license_scanning_copy=:business_license_scanning_copy,legal_representative_id_front_photo=:legal_representative_id_front_photo,legal_representative_id_back_photo=:legal_representative_id_back_photo,legal_representative_id_photo=:legal_representative_id_photo,legal_representative_id_number=:legal_representative_id_number where merchant_id=:id';
            } else {

                $sql = 'insert into t_merchant_detail(merchant_id,registration_no,business_license_scanning_copy,legal_representative_id_front_photo,legal_representative_id_back_photo,legal_representative_id_photo,
legal_representative_id_number)VALUES (:id,:registration_no,:business_license_scanning_copy,:legal_representative_id_front_photo,:legal_representative_id_back_photo,:legal_representative_id_photo,:legal_representative_id_number)';
            }

            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $id);
            $cmd->bindValue(':registration_no', $registration_no);
            $cmd->bindValue(':business_license_scanning_copy', $business_license_scanning_copy);
            $cmd->bindValue(':legal_representative_id_front_photo', $legal_representative_id_front_photo);
            $cmd->bindValue(':legal_representative_id_back_photo', $legal_representative_id_back_photo);
            $cmd->bindValue(':legal_representative_id_photo', $legal_representative_id_photo);
            $cmd->bindValue(':legal_representative_id_number', $legal_representative_id_number);
//            var_dump($cmd->rawSql);
            $result2 = DbCacheUtility::execute($cmd);

            $auth_record_id = Tools::db_uuid();
            $sql = 'INSERT INTO t_merchant_auth_record(id, merchant_id, status) VALUES(:id, :merchantId, 0);';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $auth_record_id);
            $cmd->bindValue(':merchantId', $id);
            $result3 = DbCacheUtility::execute($cmd);

            //调用自动审核功能 营业执照号码、公司名称、法人名称与用户填的一样自动通过审核
            $auto_auth_data = self::getBusinessLicenseScanningCopy($business_license_scanning_copy);
            if ($auto_auth_data) {
                $company_name = $auto_auth_data['name']; //公司名称
                $person = $auto_auth_data['person']; //法人名称
                $reg_num = $auto_auth_data['reg_num']; //法人注册号

//                var_dump($company_name);var_dump($name);var_dump($reg_num);var_dump($registration_no);exit;
                if ($company_name == $name && $reg_num == $registration_no) {
                    $sql = 'UPDATE t_merchant_auth_record SET status = 1 WHERE id = :id';
                    $cmd = \Yii::$app->db->createCommand($sql);
                    $cmd->bindValue(':id', $auth_record_id);
                    DbCacheUtility::execute($cmd);

                    $sql = 'UPDATE t_merchant SET is_auth = 1 WHERE id = :id';
                    $cmd = \Yii::$app->db->createCommand($sql);
                    $cmd->bindValue(':id', $id);
                    DbCacheUtility::execute($cmd);

                    $auth_result = true;
                }
            }

            $transaction->commit();
            $result = [
                'id' =>$id,
                'auth_result' => $auth_result
            ];
            return $result;
        } catch (\Exception $e) {
            $transaction->rollBack();
        }

        return null;


        //var_dump($cmd->rawSql);
        // var_dump($cmd);exit;
        // $result = $cmd->execute();
        // var_dump($result);
//        exit;
//        if ($result > 0) {
//            return $id;
//        } else {
//            return null;
//        }

    }

    public static function getBusinessLicenseScanningCopy($business_license_scanning_copy)
    {
        $url = $business_license_scanning_copy;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $path_name = '../web/download/' . date('YmdHis') . $filename;
        $resource = fopen($path_name, 'a');
        fwrite($resource, $file);
        fclose($resource);
        $base64_str = base64_encode(file_get_contents($path_name));

        if (file_exists($path_name)) {
            $host = "https://dm-58.data.aliyun.com";
            $path = "/rest/160601/ocr/ocr_business_license.json";
            $method = "POST";
            $appcode = \Yii::$app->params['ali_print_app_code'];
            $headers = array();
            array_push($headers, "Authorization:APPCODE " . $appcode);
            //根据API的要求，定义相对应的Content-Type
            array_push($headers, "Content-Type" . ":" . "application/json; charset=UTF-8");
            $querys = "";
            $bodys = "{\"inputs\":[{\"image\":{\"dataType\":50,\"dataValue\":\"$base64_str\"}}]}";

            $url = $host . $path;
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_FAILONERROR, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HEADER, false);
            if (1 == strpos("$" . $host, "https://")) {
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            }
            curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
            $result = curl_exec($curl);
//            file_put_contents( '../web/download/test.txt',$result);

            $result = json_decode($result, true);
            if (isset($result['outputs'][0]['outputValue']['dataValue'])) {
                $dataValue = $result['outputs'][0]['outputValue']['dataValue'];
                $dataValue = json_decode($dataValue, true);

                return $dataValue;
            }

            unlink($path_name);
        }

        return false;
    }

    public static function getAdIndustryTypeById()
    {
        $cmd = \Yii::$app->db->createCommand('
            select * from t_ad_industry_type');
        // $cmd->bindValue(':id', $id);
        $item = DbCacheUtility::queryAll($cmd);
        return $item;
    }

    /**
     * 新增保存广告内容(提交审核)
     * @param $industry_type_id
     * @param $ad_title
     */
    public static function saveAd($merchant_id, $industry_type_id, $ad_title, $content, $lon, $lat, $video, $image_main, $image_urls)
    {

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            //do sql
            $id = Tools::db_uuid();
            $cmd = \Yii::$app->db->createCommand('insert into t_ad (id,merchant_id,industry_type_id,title,content,lon,lat,video,status)values(:id,:merchant_id,:industry_type_id,:title,:content,:lon,:lat,:video,20)');

            $cmd->bindValue(':id', $id);
            $cmd->bindValue(':merchant_id', $merchant_id);
            $cmd->bindValue(':industry_type_id', $industry_type_id);
            $cmd->bindValue(':title', $ad_title);
            $cmd->bindValue(':content', $content);
            $cmd->bindValue(':lon', $lon);
            $cmd->bindValue(':lat', $lat);
            $cmd->bindValue(':video', $video);

//        var_dump($cmd->rawSql);exit;
            DbCacheUtility::execute($cmd);

            //判断是否特殊广告根据$industry_type_id
            if ($industry_type_id) {
                $cmd = \Yii::$app->db->createCommand('SELECT count(1) from t_ad_industry_type where id = :id AND is_special = 1 ');
                $cmd->bindValue(':id', $industry_type_id);
                $count = DbCacheUtility::queryScalar($cmd);
                if ($count > 0) {
                    $cmd = \Yii::$app->db->createCommand('INSERT INTO t_ad_special (ad_id, file_url, pay_status) 
                                                          VALUES (:ad_id, :file_url, 0)');
                    $cmd->bindValue(':ad_id', $id);
                    $cmd->bindValue(':file_url', '');
                    DbCacheUtility::execute($cmd);
                }
            }

            $t_id = Tools::db_uuid();
            $cmd = \Yii::$app->db->createCommand('insert into t_file (id,url)VALUES (:t_id,:url)');
//            $cmd->bindValue('id2',$id2);
            $cmd->bindValue(':t_id', $t_id);
            $cmd->bindValue(':url', $image_main);
            // var_dump($cmd->rawSql);
            DbCacheUtility::execute($cmd);


            // $cmd->bindValues('image_urls',$image_urls);
            // var_dump($image_urls);
            $id3 = Tools::db_uuid();
            $cmd = \Yii::$app->db->createCommand('insert into t_ad_image (id,image_id,`type`,ad_id)VALUES (:id3,:t_id,1,:id)');
//            $cmd->bindValue('id2',$id2);
            $cmd->bindValue(':id3', $id3);
            $cmd->bindValue(':t_id', $t_id);
            $cmd->bindValue(':id', $id);
            // var_dump($cmd->rawSql);
            DbCacheUtility::execute($cmd);

            //$id4 = Tools::db_uuid();
            $cmd = \Yii::$app->db->createCommand('insert into t_ad_times (ad_id,times)VALUES (:id4,0)');
//            $cmd->bindValue('id2',$id2);
            $cmd->bindValue(':id4', $id);
            DbCacheUtility::execute($cmd);

            if (is_array($image_urls)) {
                foreach ($image_urls as $url) {
                    $idn = Tools::db_uuid();
                    $cmd = \Yii::$app->db->createCommand('insert into t_file (id,url)VALUES (:idn,:url)');
                    $cmd->bindValue('idn', $idn);
                    $cmd->bindValue(':url', $url);
                    // var_dump($cmd->rawSql);
                    DbCacheUtility::execute($cmd);


                    $id2 = Tools::db_uuid();
                    $cmd = \Yii::$app->db->createCommand('insert into t_ad_image (id,image_id,`type`,ad_id)VALUES (:id2,:t_id,2,:ad_id)');
                    $cmd->bindValue('id2', $id2);
                    $cmd->bindValue(':t_id', $idn);
                    $cmd->bindValue(':ad_id', $id);
                    // var_dump($cmd->rawSql);
                    DbCacheUtility::execute($cmd);
                }
            }
            //var_dump($image_urls);
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
//            var_dump('rollback');exit;
            return null;
        }


        return $id;

    }

    /**
     * 获取当前商户已发布、已开始、已结束广告
     */
    public static function getAdByMerchantId($page, $pageSize, $merchantId)
    {
        $cmd = \Yii::$app->db->createCommand('select * from t_ad where merchant_id=:merchantId and status>=40  order by create_datetime DESC
            LIMIT :offset , :limit');
        $cmd->bindValue(':merchantId', $merchantId);
        $cmd->bindValue(':offset', $page * $pageSize);
        $cmd->bindValue(':limit', $pageSize * 1);
        // $cmd->bindValue(':status',$statusSQL);
//        var_dump($cmd->rawSql);
        $items = DbCacheUtility::queryAll($cmd);
        return $items;
    }

    /**
     * 增加意见回馈
     * @param $content
     * @param $origin
     * @param $origin_id
     */
    public static function addFeedback($content, $origin, $origin_id)
    {
        $id = Tools::db_uuid();
        $has_read = 0;
        $cmd = \Yii::$app->db->createCommand('insert into t_feedback(id,content,origin,origin_id,has_read)VALUES (:id,:content,:origin,:origin_id,:has_read)');
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':content', $content);
        $cmd->bindValue(':origin', $origin);
        $cmd->bindValue(':origin_id', $origin_id);
        $cmd->bindValue(':has_read', $has_read);
        DbCacheUtility::execute($cmd);
    }

    /**
     * 查询余额
     * @param $id
     * @return mixed
     */
    public static function queryAmount($id)
    {
        $cmd = \Yii::$app->db->createCommand('select `amount` from t_merchant where id =:id');
        $cmd->bindValue('id', $id);
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    /**
     * 查询当前商户已开通的平台
     * @return mixed
     */
    public static function getGroupsByMerchantId($id)
    {
        $cmd = \Yii::$app->db->createCommand('select * from t_group where id in (select group_id from t_group_merchant_relation where t_group_merchant_relation.merchant_id=:id)');
        $cmd->bindValue(':id', $id);
        $item = DbCacheUtility::queryAll($cmd);
        return $item;
    }

    /**
     * 加入平台
     * @param $id
     * @param $keyword
     * @param $name
     * @param $tel
     */
    public static function applyGroup($id, $keyword, $name, $tel)
    {

        //查询平台关键字
        $cmd = \Yii::$app->db->createCommand('select id from t_group where `name` like :keyword');
        $keyword = '%' . $keyword . '%';
        $cmd->bindValue(':keyword', $keyword);

        $item = DbCacheUtility::queryOne($cmd);
        if ($item == null)
            return null;

        //var_dump($item['id']);
        //插入记录
        $group_id = $item['id'];


        $cmd = \Yii::$app->db->createCommand('insert into t_merchant_group(group_id,merchant_id,`keyword`)VALUES (:group_id,:merchant_id,:keyword)');
        //var_dump($group_id);
        $cmd->bindValue(':group_id', $group_id);
        $cmd->bindValue(':merchant_id', $id);
        $cmd->bindValue(':keyword', $keyword);
        //var_dump($cmd->rawSql);
        DbCacheUtility::execute($cmd);
        return $group_id;
    }


    /**
     * 退出平台
     * @param $merchant_id
     * @param $group_id
     * @return int
     */
    public static function quitAGroup($merchant_id, $group_id)
    {
        $cmd = \Yii::$app->db->createCommand('delete from t_merchant_group where group_id=:group_id and merchant_id=:merchant_id');
        //var_dump($group_id);
        $cmd->bindValue(':group_id', $group_id);
        $cmd->bindValue(':merchant_id', $merchant_id);
        //$cmd->bindValue(':keyword',$keyword);
        //var_dump($cmd->rawSql);
        $item = DbCacheUtility::execute($cmd);
        return $item;
    }


    /**
     * 商户支付记录
     * @param $merchant_id
     * @param $amount
     * @param $pay_mode
     * @param $type
     * @param $origin_id
     * @return int
     */
    public static function addMerchantPayRecord($merchant_id, $amount, $pay_mode, $type, $origin_id)
    {

        $cmd = \Yii::$app->db->createCommand('insert into t_merchant_pay_record(id,merchant_id,amount,pay_mode,`type`,origin_id)VALUES (:id,:merchant_id,:amount,:pay_mode,:type,:origin_id)');
        $id = Tools::db_uuid();
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':merchant_id', $merchant_id);
        $cmd->bindValue(':amount', $amount);
        $cmd->bindValue(':pay_mode', $pay_mode);
        $cmd->bindValue(':type', $type);

        ////////????????????////////////
        $cmd->bindValue(':origin_id', $origin_id);

        $item = DbCacheUtility::execute($cmd);
        return $item;
    }
//
//    public static function getGroups()
//    {
//        $cmd = \Yii::$app->db->createCommand('select merchant_group_id,`keyword` from t_merchant_group');
//
//
//        $item = DbCacheUtility::queryAll($cmd);
//        return $item;
//    }

    /**
     * @param $page
     * @param $pageSize
     * @param $lon
     * @param $lat
     * @param $search_range
     * @param $tag  用户标签
     * @param $serach_word 关键字
     * @return mixed
     */
    public static function getUserList($page, $pageSize, $lon, $lat, $search_range, $tag, $occupation, $company, $serach_word, $merchant_id, $hobby, $group_id, $school, $age_start, $age_end, $gender, $isTourist)
    {
        // select * from sb_user_geo order by ACOS(SIN(('.$city_lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$city_lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$city_lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380

        $squares = Tools::returnSquarePoint($lon, $lat, $search_range);


//        var_dump($squares);
//        var_dump('sq:'.$squares['right-bottom']['lat']);
        $rl = $squares['right-bottom']['lat'];
        $ll = $squares['left-top']['lat'];
        $ltl = $squares['left-top']['lng'];
        $rbl = $squares['right-bottom']['lng'];

        $tmp = '';
        if ($hobby != '' && $hobby != ' ') {
            $hobby = "'%$hobby%'";
            $tmp = $tmp . ' and hobby like ' . $hobby;
        }
        if ($school != '' && $school != ' ') {
            $school = "'%$school%'";
            $tmp = $tmp . ' and school like ' . $school;
        }
        if ($tag != '' && $tag != ' ') {
            $tag = "'%$tag%'";
            $tmp = $tmp . ' and tag like ' . $tag;
        }
        if ($occupation != '' && $occupation != ' ') {
            $occupation = "'%$occupation%'";
            $tmp = $tmp . ' and occupation like ' . $occupation;
        }
        if ($company != '' && $company != ' ') {
            $company = "'%$company%'";
            $tmp = $tmp . ' and occupation like ' . $company;
        }

        if ($gender != -1) {
            $tmp = $tmp . ' and gender =' . $gender;
        }

        if ($isTourist != 0) {
            $tmp = $tmp . ' and isTourist = 1';
        }
//var_dump("group_id:$group_id");
        if ($group_id != '') {
            $tmp = $tmp . ' and id in(select user_id from t_group_user_relation where group_id=\'' . $group_id . '\')';
//            var_dump("temp:$tmp");
        }

        $sql = 'select id,`nick_name`,gravatar,tag from `t_user` where lat<>0 and lat>:rl and lat<:ll and lon>:ltl and lon<:rbl ' . $tmp . ' and age>= :age_start and age<=:age_end
            order by create_datetime DESC
            LIMIT :offset , :limit';

//var_dump("sql:$sql");

//        if ($tag != 0) {
//            $sql = 'select id,`nick_name`,gravatar,tag from `t_user` where lat<>0 and lat>:rl and lat<:ll and lon>:ltl and lon<:rbl and tag =:tag
//            order by create_datetime DESC
//            LIMIT :offset , :limit';
//        }
        //$sql1 = '';
//        if ($user_type == 1) {
//
//            $sql = 'select t1.id,t1.`nick_name`,t1.gravatar,t1.tag from `t_user` as t1,t_user_merchant_follow as t2 where t1.lat<>0 and t1.lat>:rl and t1.lat<:ll and t1.lon>:ltl and t1.lon<:rbl and t2.user_id = t1.id and t2.merchant_id=:merchant_id
//            order by t1.create_datetime DESC
//            LIMIT :offset , :limit';
//        } else if ($user_type == 2) {//未实现
//            $sql = 'select t1.id,t1.`nick_name`,t1.gravatar,t1.tag from `t_user` as t1,t_user_merchant_follow as t2 where t1.lat<>0 and t1.lat>:rl and t1.lat<:ll and t1.lon>:ltl and t1.lon<:rbl and t2.user_id = t1.id and t2.merchant_id=:merchant_id
//            order by t1.create_datetime DESC
//            LIMIT :offset , :limit';
//        }

        $cmd = \Yii::$app->db->createCommand($sql);
        // $cmd->bindValue(':sql1',$sql1);
        $cmd->bindValue(':offset', $page * $pageSize);
        $cmd->bindValue(':limit', $pageSize * 1);
        $cmd->bindValue(':rl', $rl);
        $cmd->bindValue(':ll', $ll);
        $cmd->bindValue(':ltl', $ltl);
        $cmd->bindValue(':rbl', $rbl);
        $cmd->bindValue(':age_start', $age_start);

        $cmd->bindValue(':age_end', $age_end);

//        if ($tag != 0)
//            $cmd->bindValue(':tag', $tag);
//        if($hobby != 0)
//            $cmd->bindValue(':hobby', $hobby);

        //        if ($user_type == 1 || $user_type == 2) {
//            $cmd->bindValue(':merchant_id', $merchant_id);
//        }
//       var_dump($cmd->rawSql); //exit;
        $items = DbCacheUtility::queryAll($cmd);
        return $items;
    }

    /**
     * 设置定向人群
     */
    public static function submitUsers($ad_id, $userIds)
    {

        $transaction = \Yii::$app->db->beginTransaction();
        try {

            $cmd = \Yii::$app->db->createCommand('delete from t_ad_cash_gift_users where ad_id=:ad_id');
            $cmd->bindValue(':ad_id', $ad_id);
//            var_dump($cmd->rawSql);
            DbCacheUtility::execute($cmd);


            $count = count($userIds);

            $cmd = \Yii::$app->db->createCommand('update t_ad_cash_gift set `count`=:count where ad_id=:ad_id');
            $cmd->bindValue(':ad_id', $ad_id);
            $cmd->bindValue(':count', $count);

//            var_dump($cmd->rawSql);
            DbCacheUtility::execute($cmd);


            foreach ($userIds as $user) {
//             var_dump($user->user_id);
                $id = Tools::db_uuid();
                $cmd = \Yii::$app->db->createCommand('insert into t_ad_cash_gift_users(id,ad_id,user_id,`status`)VALUES (:id,:ad_id,:user_id,1)');
//             $id = Tools::db_uuid();
                $cmd->bindValue(':ad_id', $ad_id);
                $cmd->bindValue(':id', $id);
                $cmd->bindValue(':user_id', $user->user_id);
//             var_dump($cmd->rawSql);
                $item = DbCacheUtility::execute($cmd);

            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            return null;
        }
        return $item;
    }

    /**
     * 支付成功后，对定用户广告用户进行推送
     * @param $ad_id
     */
    public static function setGiftPaySuccess($ad_id)
    {
        $cmd = \Yii::$app->db->createCommand('update t_ad_cash_gift_users set `status`=1 where ad_id=:ad_id');
        $cmd->bindValue(':ad_id', $ad_id);
//             var_dump($cmd->rawSql);
        $co = DbCacheUtility::execute($cmd);

        if ($co < 1)
            return;

        $cmd = \Yii::$app->db->createCommand('select t0.user_id,t1.push_id from t_ad_cash_gift_users t0 LEFT JOIN t_user t1 on t1.id=t0.user_id  where t0.ad_id=:ad_id and t0.`status`= 1');
        $cmd->bindValue(':ad_id', $ad_id);
//             var_dump($cmd->rawSql);
        $items = DbCacheUtility::queryAll($cmd);

        if (is_null($items)) {
            return;
        }

        foreach ($items as $user) {
            if ($user['push_id']) {
                GetuiClient::pushMessageToSingle($user['push_id'], '您收到一个红包，请赶紧登录屏主客户端查收');
            } else {
                GetuiClient::pushMessageToSingleWithLog($user['push_id'], '您收到一个红包，请赶紧登录屏主客户端查收', '[setGiftPaySuccess]; user_id:' . $user['user_id'] . '; ad_id:' . $ad_id);
            }
        }
    }

    /**
     * 设置红包口令
     * @param $ad_id
     * @param $word
     */
    public static function setGiftWord($ad_id, $question, $answer_right, $answer_error)
    {
        $cmd = \Yii::$app->db->createCommand('update t_ad_cash_gift set question=:question,answer_right=:answer_right,answer_error=:answer_error where ad_id=:ad_id');
        // $id = Tools::db_uuid();
        $cmd->bindValue(':ad_id', $ad_id);
        $cmd->bindValue(':question', $question);
        $cmd->bindValue(':answer_right', $answer_right);
        $cmd->bindValue(':answer_error', $answer_error);

        $item = DbCacheUtility::execute($cmd);
//        var_dump($item);
        return $item > 0;
    }

    /**
     * 发布定点广告
     * @param $lon
     * @param $lat
     * @param $search_range
     */
    public static function releaseAdByArea($ad_id, $lon, $lat, $search_range)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        try {

            $cmd = \Yii::$app->db->createCommand('update t_ad set lon = :lon,lat = :lat where id=:ad_id');
//             $id = Tools::db_uuid();
            $cmd->bindValue(':lon', $lon);
            $cmd->bindValue(':lat', $lat);
            $cmd->bindValue(':ad_id', $ad_id);
            $item = DbCacheUtility::execute($cmd);

            $cmd = \Yii::$app->db->createCommand('update t_ad_cash_gift set `range` = :range where ad_id=:ad_id');
//             $id = Tools::db_uuid();
            $cmd->bindValue(':range', $search_range);
//            $cmd->bindValue(':lat',$lat);
            $cmd->bindValue(':ad_id', $ad_id);
//            var_dump($cmd->rawSql);
            $item = DbCacheUtility::execute($cmd);

            $transaction->commit();

            $item = self::getUsersByPositionAndRange($lon, $lat, $search_range);


            return $item;
        } catch (\Exception $e) {
            $transaction->rollBack();
            return null;
        }
    }

    /**
     * 返回附近所有用户
     * @param $lon
     * @param $lat
     * @param $search_range
     * @return mixed
     */
    public static function getUsersByPositionAndRange($lon, $lat, $search_range)
    {
        // select * from sb_user_geo order by ACOS(SIN(('.$city_lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$city_lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$city_lng.' * 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380

        $squares = Tools::returnSquarePoint($lon, $lat, $search_range);


//        var_dump($squares);
//        var_dump('sq:'.$squares['right-bottom']['lat']);
        $rl = $squares['right-bottom']['lat'];
        $ll = $squares['left-top']['lat'];
        $ltl = $squares['left-top']['lng'];
        $rbl = $squares['right-bottom']['lng'];

        $sql = '
            select count(id) as count from `t_user` where lat<>0 and lat>:rl and lat<:ll and lon>:ltl and lon<:rbl
            order by create_datetime DESC;';
        //$sql1 = '';


        $cmd = \Yii::$app->db->createCommand($sql);
        // $cmd->bindValue(':sql1',$sql1);

        $cmd->bindValue(':rl', $rl);
        $cmd->bindValue(':ll', $ll);
        $cmd->bindValue(':ltl', $ltl);
        $cmd->bindValue(':rbl', $rbl);

//       var_dump($cmd->rawSql);
        $items = DbCacheUtility::queryOne($cmd);
        return $items;
    }

    /**
     * 设置定点广告总红包个数及总金额
     * @param $ad_id
     * @param $count
     * @param $total
     * @return mixed
     */
    public static function setAreaAdGiftCount($ad_id, $count, $total)
    {
        $cmd = \Yii::$app->db->createCommand('select ad_id from t_ad_cash_gift where ad_id=:ad_id');
        $cmd->bindValue(':ad_id', $ad_id);
        $temp = DbCacheUtility::queryScalar($cmd);

        $sql = '';
//        var_dump($temp);exit;
//        $one_cash = $total/$count*(1-Merchant::BIGGROUP);
        $one_cash = $total / $count;
        //此处应该为大平台、代理商入账


        //////////////////////////

        if ($temp <> '' || $temp != null) {
            $sql = 'update t_ad_cash_gift set `count`=:count,one_cash=:one_cash where ad_id=:ad_id';
            $cmd = \Yii::$app->db->createCommand($sql);

            $cmd->bindValue(':ad_id', $ad_id);
            $cmd->bindValue(':one_cash', $one_cash);
            $cmd->bindValue(':count', $count);

            //        $cmd->bindValue(':total', $total);
            $item = DbCacheUtility::execute($cmd);
        } else {
            return -1;
        }


        return $item;
    }


    public static function getMerchantFuns($merchant_id, $page, $pageSize)
    {
        $cmd = \Yii::$app->db->createCommand('select id,nick_name,gravatar from t_user left join t_user_merchant_follow on user_id = id where merchant_id = :merchant_id  order by create_datetime DESC LIMIT :offset , :limit');
        $cmd->bindValue(':offset', $page * $pageSize);
        $cmd->bindValue(':limit', $pageSize * 1);
        $cmd->bindValue(':merchant_id', $merchant_id);
        $item = DbCacheUtility::queryAll($cmd);
        return $item;
    }

    /**
     * 获取广告阅读、消费次数、广告
     * @param $ad_id
     * @return mixed
     */
    public static function getAdReadTimes($merchant_id)
    {
        $cmd = \Yii::$app->db->createCommand('select sum(t1.times) times ,sum(t1.consume_times) consume_times from t_ad_times t1 LEFT JOIN t_ad t2 ON t1.ad_id = t2.id where t2.merchant_id=:merchant_id');
        $cmd->bindValue(':merchant_id', $merchant_id);
//        var_dump($cmd->rawSql);exit;
        $item = DbCacheUtility::queryOne($cmd);
        $item['data_publish_date'] = date("Y/m/d");
        if (is_null($item)) {
            $item['times'] = 0;
            $item['consume_times'] = 0;
        } elseif (is_null($item['times'])) {
            $item['times'] = 0;
        } elseif (is_null($item['consume_times'])) {
            $item['consume_times'] = 0;
        }
        return $item;
    }

    public static function getMerchantAuthStatus($merchant_id)
    {
        $cmd = \Yii::$app->db->createCommand('select is_auth from t_merchant where id=:merchant_id and is_enabled=1');
        $cmd->bindValue(':merchant_id', $merchant_id);
//        var_dump($cmd->rawSql);exit;
        $item = DbCacheUtility::queryOne($cmd);
        return $item;
    }

    public static function getMessages($type, $page, $pageSize)
    {
        $cmd = \Yii::$app->db->createCommand('select title,content,create_datetime from t_system_message where `type`=:type ORDER BY create_datetime DESC LIMIT :offset , :limit');
        $cmd->bindValue(':offset', $page * $pageSize);
        $cmd->bindValue(':limit', $pageSize * 1);
        $cmd->bindValue(':type', $type);
        $item = DbCacheUtility::queryAll($cmd);
        return $item;
    }

    public static function getSaleArticleList($page, $pageSize)
    {
        $cmd = \Yii::$app->db->createCommand('select id,title from t_sale_article where is_enabled=0 ORDER BY create_datetime DESC LIMIT :offset , :limit');
        $cmd->bindValue(':offset', $page * $pageSize);
        $cmd->bindValue(':limit', $pageSize * 1);
//        var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryAll($cmd);
        return $item;
    }

    public static function getSaleArticle($id)
    {
//        $cmd = \Yii::$app->db->createCommand('select detail_html from t_sale_article where id=:id');
//        $cmd->bindValue(':id', $id);
//        $item = DbCacheUtility::queryOne($cmd);
//
//        $file = "../views/sale-article/$id.html";
//        if (is_readable($file) == false) {
//            self::createSaleArticaleHtml($id,$item['detail_html']);
//        } else {
//            self::overrideSaleArticalHtml($id,$item['detail_html']);
//        }
//
//        return 'http://119.23.110.230/views/sale-article/'.$id.'.html';
        return "http://119.23.110.230/site/sale-article-show?id=$id";
    }

    static function overrideSaleArticalHtml($id, $content)
    {
        $myfile = fopen("../views/sale-article/$id.html", "w") or die("Unable to open file!");
        fwrite($myfile, $content);
        fclose($myfile);
    }

    static function createSaleArticaleHtml($id, $content)
    {

        $myfile = fopen("../views/sale-article/$id.html", "w") or die("Unable to open file!");
        fwrite($myfile, $content);
        fclose($myfile);

    }


    public static function getAdReport($merchant_id)
    {
        $cmd = \Yii::$app->db->createCommand('select t1.id,t1.`title`,t4.times,t3.url,t1.publish_datetime,t5.`name`,t1.lon,t1.lat from t_ad t1 LEFT JOIN t_ad_image t2 ON t1.id=t2.ad_id and t2.`type`=1 LEFT JOIN t_file t3 on t3.id = t2.image_id LEFT JOIN t_ad_times t4 ON t4.ad_id=t1.id LEFT JOIN t_ad_industry_type t5 ON t5.id=t1.industry_type_id where merchant_id=:id and t1.`status`>=40');
        $cmd->bindValue(':id', $merchant_id);
//        var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryAll($cmd);
        if (!is_null($item)) {
            foreach ($item as &$ad) {
//                var_dump($ad['times']);
                if (is_null($ad['times'])) {
//                    var_dump('in if');
                    $ad['times'] = 0;
                }
            }
        }
        return $item;
    }

    public static function updateAreaAdUsers()
    {

        $cmd = \Yii::$app->db->createCommand('select t1.ad_id,t1.range,t0.lon,t0.lat,ifnull(t1.count,0) as `count`,ifnull(t0.create_datetime,0) as create_datetime from t_ad_cash_gift t1
                                                   LEFT JOIN t_ad t0 on t0.id=t1.ad_id
                                                     where publish_type=2 and pay_status=1 and end_datetime > NOW()');
//        $cmd->bindValue(':id', $merchant_id);
//        var_dump($cmd->rawSql);
        $ads = DbCacheUtility::queryAll($cmd);

        foreach ($ads as $ad) {
            $ad_sent_count = 0;//广告已发放个数

            //查询广告设定红包个数
            $sql = 'select ifnull(count(user_id),0) from t_ad_cash_gift_users where ad_id=:ad_id and `status`=2';
//            $sql = 'select id from t_user where lat <> 0 ';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':ad_id', $ad['ad_id']);

//            var_dump($cmd->rawSql);
            $ad_sent_count = DbCacheUtility::queryScalar($cmd);
            var_dump('id:' . $ad['ad_id'] . '.count:' . $ad['count'] . '.ad_sent_count:' . $ad_sent_count . '.time:' . $ad['create_datetime']);
            if ($ad_sent_count >= $ad['count'])
                continue;

            $squares = Tools::returnSquarePoint($ad['lon'], $ad['lat'], $ad['range']);

            $rl = $squares['right-bottom']['lat'];
            $ll = $squares['left-top']['lat'];
            $ltl = $squares['left-top']['lng'];
            $rbl = $squares['right-bottom']['lng'];

            $sql = 'select t1.id from t_user t1 where t1.lat<>0 and t1.lat>:rl and t1.lat<:ll and t1.lon>:ltl and t1.lon<:rbl 
                    and id NOT IN (select t0.user_id from t_ad_cash_gift_users t0 where t0.ad_id=:ad_id and (t0.`status`=2 or t0.`status`=1))';
//            $sql = 'select id from t_user where lat <> 0 ';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':rl', $rl);
            $cmd->bindValue(':ll', $ll);
            $cmd->bindValue(':ltl', $ltl);
            $cmd->bindValue(':rbl', $rbl);
            $cmd->bindValue('ad_id', $ad['ad_id']);

            var_dump($cmd->rawSql);
            $users = DbCacheUtility::queryAll($cmd);
            var_dump('-------area users: ' . serialize($users) . '--------------');
            foreach ($users as $user) {
//              var_dump('----------for begin------------');
                $sql = 'select t1.id as user_id,t0.`status`,t1.push_id from t_ad_cash_gift_users t0 LEFT JOIN t_user t1 on t1.id=t0.user_id where t0.ad_id=:ad_id and t0.user_id=:user_id';
                $cmd = \Yii::$app->db->createCommand($sql);

                $cmd->bindValue('ad_id', $ad['ad_id']);
                $cmd->bindValue('user_id', $user['id']);
                $is_new = false;
                try {
                    var_dump($cmd->rawSql);
                    $c_user = DbCacheUtility::queryOne($cmd);

                    if(empty($c_user)){
                        $is_new = true;
                        $sql = 'select id as user_id,(select 0) as `status`,push_id from t_user where id=:user_id';
                        $cmd = \Yii::$app->db->createCommand($sql);
                        $cmd->bindValue('user_id', $user['id']);
                        $c_user = DbCacheUtility::queryOne($cmd);
                    }

                    var_dump('user_id:'.$c_user['user_id'].' status:'.$c_user['status'].' push_id:'.$c_user['push_id']);
//status:
//                    if(is_null($c_user))
//                        continue;
                } catch (PDOException $e) {
                    print "错误: " . $e->getMessage() . "<br />";
                    print "行号: " . $e->getLine() . "<br />";
                    die();
                }
//                var_dump($c_user['user_id'].' '.$c_user['status']);

//                var_dump(serialize($c_user).' pu:'.$c_user['push_id']);
                if ($is_new) {
                    $i = Tools::db_uuid();
                    $sql = 'insert into t_ad_cash_gift_users (id,ad_id,user_id,`status`)VALUES (:id,:ad_id,:user_id,1)';
                    $cmd = \Yii::$app->db->createCommand($sql);
                    $cmd->bindValue(':id', $i);

                    $cmd->bindValue('ad_id', $ad['ad_id']);
                    $cmd->bindValue('user_id', $user['id']);
                    var_dump($cmd->rawSql);

                    DbCacheUtility::execute($cmd);
                } else {
                    var_dump('status:' . $c_user['status']);
                    if ($c_user['status'] == 2 || $c_user['status'] == 1)
                        continue;
                    $sql = 'update t_ad_cash_gift_users set `status`=1 where ad_id=:ad_id and user_id=:user_id and `status`<>2';

                    $cmd = \Yii::$app->db->createCommand($sql);
                    $cmd->bindValue('ad_id', $ad['ad_id']);
                    $cmd->bindValue('user_id', $user['id']);
                    var_dump($cmd->rawSql);

                    DbCacheUtility::execute($cmd);
                }
                var_dump('----ready to push-----');
                var_dump($c_user['user_id']);
                var_dump($c_user['push_id']);
                //向用户推送消息
                if (!is_null($c_user['push_id'])) {
                    var_dump('cccc' . $c_user['push_id']);
                    GetuiClient::pushMessageToSingle($c_user['push_id'], '你收到专属红包，请前往领取！');
                } else {
                    var_dump('push id is null');
                    GetuiClient::pushMessageToSingleWithLog($c_user['push_id'], '你收到专属红包，请前往领取！', '[updateAreaAdUsers]; ' . 'user_id:' . $user['id'] . '; ad_id:' . $ad['ad_id']);
                }
                $ad_sent_count = $ad_sent_count + 1;
                if ($ad_sent_count >= $ad['count'])
                    break;
                var_dump('----------for begin------------');
            }
            var_dump('---------------------ad end-----------------------');
        }


    }

    public static function setPushId($merchant_id, $push_id)
    {
        $sql = 'update t_merchant set push_id=:push_id where id=:id';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $merchant_id);
        $cmd->bindValue('push_id', $push_id);
        return DbCacheUtility::execute($cmd);
    }

    /**
     * 再次发布广告（复制一个广告）
     * @param $merchant_id
     * @param $ad_id
     * @return null
     */
    public static function publishAdAgain($merchant_id, $ad_id)
    {
        $re = null;
        $sql = 'select * from t_ad where id=:ad_id';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':ad_id', $ad_id);
        $ad = DbCacheUtility::queryOne($cmd);

        $transaction = \Yii::$app->db->beginTransaction();
        try {


            $new_id = Tools::db_uuid();
            $sql = 'insert into t_ad(id,merchant_id,industry_type_id,title,content,lon,lat,video,publish_datetime,`status`)VALUES(:new_id,:merchant_id,:industry_type_id,:title,:content,:lon,:lat,:video,now(),20) ';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':new_id', $new_id);
            $cmd->bindValue(':merchant_id', $merchant_id);
            $cmd->bindValue(':industry_type_id', $ad['industry_type_id']);
            $cmd->bindValue(':title', $ad['title']);
            $cmd->bindValue(':content', $ad['content']);
            $cmd->bindValue(':lon', $ad['lon']);
            $cmd->bindValue(':lat', $ad['lat']);
            $cmd->bindValue(':video', $ad['video']);
//var_dump($cmd->rawSql);
            DbCacheUtility::execute($cmd);

            $new_id2 = Tools::db_uuid();
            $sql = 'insert into t_ad_auth_record (id,ad_id,`status`)VALUES (:new_id2,:ad_id,1)';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':ad_id', $new_id);
            $cmd->bindValue(':new_id2', $new_id2);
//            var_dump($cmd->rawSql);

            $re = DbCacheUtility::execute($cmd);


            $sql = 'SELECT t0.id,t1.`type` from t_file t0 left join t_ad_image t1 on t1.image_id=t0.id where t1.ad_id=:ad_id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':ad_id', $ad_id);
//            var_dump($cmd->rawSql);

            $files = DbCacheUtility::queryAll($cmd);

            foreach ($files as $fi) {
                $id2 = Tools::db_uuid();
                $cmd = \Yii::$app->db->createCommand('insert into t_ad_image (id,image_id,`type`,ad_id)VALUES (:id2,:t_id,:type_,:ad_id)');
                $cmd->bindValue(':id2', $id2);
                $cmd->bindValue(':t_id', $fi['id']);
                $cmd->bindValue(':type_', $fi['type']);
                $cmd->bindValue(':ad_id', $new_id);
//                 var_dump($cmd->rawSql);
                DbCacheUtility::execute($cmd);
            }

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
//            var_dump('rollback');exit;
            return null;
        }
        return $re;
    }

    /**
     * 交易成功后，给云联惠买家赠送积分
     * @param $trade_no 本系统订单号
     * @param $amount 交易金额
     * @param $goods 商品描述
     * @param $mobile 用户手机号
     * @param $subject 订单名称
     */
    public static function sendYLHPoint($trade_no, $amount, $goods_desc = '屏主广告', $subject1 = '屏主广告', $merchant_id)
    {
        $token = self::getYLHToken();
        $cmd = \Yii::$app->db->createCommand('select phone from t_merchant where id=:id');
        $cmd->bindValue(':id', $merchant_id);
//                 var_dump($cmd->rawSql);
        $mobile = DbCacheUtility::queryScalar($cmd);
        $config = [
            //应用ID
            'client_id' => '4c20e25d',
            //应用密钥
            'client_secret' => 'a04896cb0b3986593ad377e739144d326dfeaa276f336e4f32e257320c462c7b',
            //应用回调地址
            'redirect_uri' => 'https://pzbdata.com/oauth/callback',
            //应用私钥，您的原始格式RSA私钥
            'client_private_key' => "MIICXAIBAAKBgQDeEmjFIhn+HwFSpCK+taWeU1qzHxotUPFyrnjz5c6Or8SntgIYUuGVl8VYkGkKWUz8FUr1vNNd/NPRNSOh8wTJiy7H//dOzhSkDp6c+CrS87qeqX+Fmj0a5g4y/Z6FDD0UpgoD6qrONbxy4vKWgy8c2XGCKt6l6V/CmyZcdd7eHQIDAQABAoGBAKITP4H41I2iZV3CS1Vyz3BRF5Y5cep28/EmI0Kmi22aHOXmMXs9KkT6ot5zbyZNbKFijPXynTUwbAt5RAtTiT6O5yuC/dfLoo1oXuw66YCirZsYVgeghnXnHFdzNi/pWponW6Lc+TtTsB85F94Pcz8RuIemlN0EwpysdkYTHZfhAkEA9sJ8wyQQy1kWVkMFSiac56towxZGZ9sx+Q6a8Vd6blJZOpD25hE/wPR6Xq/xq8nlGNSehf19Xoac2XGHpYNPVQJBAOZjQdf6QAKERU47qH9G/h8JdUqipNDNFF8nWM8cAmHfmiq9SNof22ek/UolWcJkTL5qTcby4E+4J4MEP9g7g6kCQAbPrYPxbek/B0fQR8gZMsGOULD5322kdkeqqIo64O1EpqPgNoB5P2pDFVGhx6j3RLSfwdRu/9PpIVE7OgROkJUCQHQu9hOO9hzOy4yqdUzKZnkMcgQThX5vDaj21MiNXX4yHzMShdzKWAEqqTltIJjxr+oO/e4oqYpKWlKuH+xSBxECQHa89i3H5qZMz9loyhabqLD227YQfcls7lCTbuRHwHuQF+IwnAk2D5uBm27PjIcqjhI9ivZYQGuCG6aZOn/tvhU=",
            //同步跳转
            'return_url' => 'https://example.com/example/return_url.php',
            //异步通知地址
            'notify_url' => 'https://example.com/example/notify_url.php',
            //云联惠API网关
            'gatewayUrl' => "https://openapi.yunlianhui.com",   //开发：openapidev  正式：openapi
            //云联惠开放平台收银台
            'gatewayPay' => "https://openpay.yunlianhui.com", //开发：openpaydev  正式：openpay
            //云联惠公钥,查看地址：https://docs.yunlianhui.com/keyManage
            'alipay_public_key' => "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDeEmjFIhn+HwFSpCK+taWeU1qzHxotUPFyrnjz5c6Or8SntgIYUuGVl8VYkGkKWUz8FUr1vNNd/NPRNSOh8wTJiy7H//dOzhSkDp6c+CrS87qeqX+Fmj0a5g4y/Z6FDD0UpgoD6qrONbxy4vKWgy8c2XGCKt6l6V/CmyZcdd7eHQIDAQAB",

        ];
        $oauth_client = new OAuth2($config['gatewayUrl'], $config['client_id'], $config['client_secret'], $config['client_private_key'], $config['redirect_uri']);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $trade_no;
        //订单名称，必填
        $subject = $subject1;
        //付款金额，必填
        $total_amount = $amount;
        //商品描述，必填
        $body = $goods_desc;
        //买家手机号
        $buyer_mobile = $mobile;
        $oauth_client = new OAuth2($config['gatewayUrl'], $config['client_id'], $config['client_secret'], $config['client_private_key'], $config['redirect_uri']);
        try {
            $result = $oauth_client->sendAnResourceRequest([
                'client_id' => $config['client_id'],
                'access_token' => $token,
                'timestamp' => (string)time(),
                'buyer_mobile' => $buyer_mobile,
                'out_trade_no' => $out_trade_no,
                'subject' => $subject,
                'body' => $body,
                'total_amount' => $total_amount,
            ], 'api/v2/returnPoints');
            $flag = $result['first_time'] ? '第一次' : '已注册';
            echo "全返成功<br />订单号：" . $result['order_id'] . "<br />订单状态：" . $result['order_status']
                . "<br />会员状态：" . $flag;
            self::saveYLHPointSendRecord($mobile, $out_trade_no, $amount, '', $result['order_id'], $result['order_status']);
        } catch (\YunLianHui\ApiException $exception) {
            print_r('接口请求失败<br> ' . '错误信息是:' . $exception->getMessage());
        }
    }

    private static function getYLHToken()
    {
        $cmd = \Yii::$app->db->createCommand('select token from t_ylh_token where id=1');
//                 var_dump($cmd->rawSql);
        return DbCacheUtility::queryScalar($cmd);
    }

    private static function saveYLHPointSendRecord($phone, $out_trade_no, $amount, $pay_id, $ylh_order_id, $ylh_order_status)
    {
        $id2 = Tools::db_uuid();
        $cmd = \Yii::$app->db->createCommand('insert into t_ylh_point_pay_record (id,phone,out_trade_no,amount,pay_id,ylh_order_id,ylh_order_status) VALUES (:id2,:phone,:out_trade_no,:amount,:pay_id,:ylh_order_id,:ylh_order_status)');
        $cmd->bindValue(':id2', $id2);
        $cmd->bindValue(':phone', $phone);
        $cmd->bindValue(':out_trade_no', $out_trade_no);
        $cmd->bindValue(':amount', $amount);
        $cmd->bindValue(':pay_id', $pay_id);
        $cmd->bindValue(':ylh_order_id', $ylh_order_id);
        $cmd->bindValue(':ylh_order_status', $ylh_order_status);
//                 var_dump($cmd->rawSql);
        DbCacheUtility::execute($cmd);
    }


    /**
     *获取云联惠会员token
     * @param $code
     * @return null
     */
    public static function getAccessToken($code)
    {
        $config = [
            //应用ID
            'client_id' => '4c20e25d',
            //应用密钥
            'client_secret' => 'a04896cb0b3986593ad377e739144d326dfeaa276f336e4f32e257320c462c7b',
            //应用回调地址
            'redirect_uri' => 'https://pzbdata.com/oauth/callback',
            //应用私钥，您的原始格式RSA私钥
            'client_private_key' => "MIICXAIBAAKBgQDeEmjFIhn+HwFSpCK+taWeU1qzHxotUPFyrnjz5c6Or8SntgIYUuGVl8VYkGkKWUz8FUr1vNNd/NPRNSOh8wTJiy7H//dOzhSkDp6c+CrS87qeqX+Fmj0a5g4y/Z6FDD0UpgoD6qrONbxy4vKWgy8c2XGCKt6l6V/CmyZcdd7eHQIDAQABAoGBAKITP4H41I2iZV3CS1Vyz3BRF5Y5cep28/EmI0Kmi22aHOXmMXs9KkT6ot5zbyZNbKFijPXynTUwbAt5RAtTiT6O5yuC/dfLoo1oXuw66YCirZsYVgeghnXnHFdzNi/pWponW6Lc+TtTsB85F94Pcz8RuIemlN0EwpysdkYTHZfhAkEA9sJ8wyQQy1kWVkMFSiac56towxZGZ9sx+Q6a8Vd6blJZOpD25hE/wPR6Xq/xq8nlGNSehf19Xoac2XGHpYNPVQJBAOZjQdf6QAKERU47qH9G/h8JdUqipNDNFF8nWM8cAmHfmiq9SNof22ek/UolWcJkTL5qTcby4E+4J4MEP9g7g6kCQAbPrYPxbek/B0fQR8gZMsGOULD5322kdkeqqIo64O1EpqPgNoB5P2pDFVGhx6j3RLSfwdRu/9PpIVE7OgROkJUCQHQu9hOO9hzOy4yqdUzKZnkMcgQThX5vDaj21MiNXX4yHzMShdzKWAEqqTltIJjxr+oO/e4oqYpKWlKuH+xSBxECQHa89i3H5qZMz9loyhabqLD227YQfcls7lCTbuRHwHuQF+IwnAk2D5uBm27PjIcqjhI9ivZYQGuCG6aZOn/tvhU=",
            //同步跳转
            'return_url' => 'https://example.com/example/return_url.php',
            //异步通知地址
            'notify_url' => 'https://example.com/example/notify_url.php',
            //云联惠API网关
            'gatewayUrl' => "https://openapi.yunlianhui.com",   //开发：openapidev  正式：openapi
            //云联惠开放平台收银台
            'gatewayPay' => "https://openpay.yunlianhui.com", //开发：openpaydev  正式：openpay
            //云联惠公钥,查看地址：https://docs.yunlianhui.com/keyManage
            'alipay_public_key' => "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDeEmjFIhn+HwFSpCK+taWeU1qzHxotUPFyrnjz5c6Or8SntgIYUuGVl8VYkGkKWUz8FUr1vNNd/NPRNSOh8wTJiy7H//dOzhSkDp6c+CrS87qeqX+Fmj0a5g4y/Z6FDD0UpgoD6qrONbxy4vKWgy8c2XGCKt6l6V/CmyZcdd7eHQIDAQAB",

        ];
        $oauth_client = new OAuth2($config['gatewayUrl'], $config['client_id'], $config['client_secret'], $config['client_private_key'], $config['redirect_uri']);
        try {
            $access_token = $oauth_client->getAccessTokenFromCode($code);
            echo "<br />code:" . $code;
            echo "换取token成功<br />令牌：" . $access_token['access_token'] . "<br />有效期：" . $access_token['expires_in']
                . "<br />作用域：" . $access_token['scope']
                . "<br />刷新令牌：" . $access_token['refresh_token'];
            return $access_token['access_token'];

        } catch (\YunLianHui\ApiException $exception) {
            print_r('接口请求失败<br> ' . '错误信息是:' . $exception->getMessage());
        }
        return null;
    }

    /**
     * 云联惠获取用户信息接口
     * @param $user_token 云联惠用户token
     */
    public static function getYLHUserInfo($user_token)
    {

        // https://openapidev.yunlianhui.com/oauth/authorize/?response_type=code&client_id=WYFX&redirect_uri=http%3A%2F%2F119.23.110.230%2Foauth%2Fcallback&state=a0cbdbd5445fc599fcba27f59f235ee3&scope=basic_info+points
        //https://openapi.yunlianhui.com/oauth/authorize/?response_type=code&client_id=4c20e25d&redirect_uri=https%3A%2F%2Fpzbdata.com%2Foauth%2Fcallback&state=a0cbdbd5445fc599fcba27f59f235ee3&scope=basic_info+points
        $config = [
            //应用ID
            'client_id' => '4c20e25d',
            //应用密钥
            'client_secret' => 'a04896cb0b3986593ad377e739144d326dfeaa276f336e4f32e257320c462c7b',
            //应用回调地址
            'redirect_uri' => 'https://pzbdata.com/oauth/callback',
            //应用私钥，您的原始格式RSA私钥
            'client_private_key' => "MIICXAIBAAKBgQDeEmjFIhn+HwFSpCK+taWeU1qzHxotUPFyrnjz5c6Or8SntgIYUuGVl8VYkGkKWUz8FUr1vNNd/NPRNSOh8wTJiy7H//dOzhSkDp6c+CrS87qeqX+Fmj0a5g4y/Z6FDD0UpgoD6qrONbxy4vKWgy8c2XGCKt6l6V/CmyZcdd7eHQIDAQABAoGBAKITP4H41I2iZV3CS1Vyz3BRF5Y5cep28/EmI0Kmi22aHOXmMXs9KkT6ot5zbyZNbKFijPXynTUwbAt5RAtTiT6O5yuC/dfLoo1oXuw66YCirZsYVgeghnXnHFdzNi/pWponW6Lc+TtTsB85F94Pcz8RuIemlN0EwpysdkYTHZfhAkEA9sJ8wyQQy1kWVkMFSiac56towxZGZ9sx+Q6a8Vd6blJZOpD25hE/wPR6Xq/xq8nlGNSehf19Xoac2XGHpYNPVQJBAOZjQdf6QAKERU47qH9G/h8JdUqipNDNFF8nWM8cAmHfmiq9SNof22ek/UolWcJkTL5qTcby4E+4J4MEP9g7g6kCQAbPrYPxbek/B0fQR8gZMsGOULD5322kdkeqqIo64O1EpqPgNoB5P2pDFVGhx6j3RLSfwdRu/9PpIVE7OgROkJUCQHQu9hOO9hzOy4yqdUzKZnkMcgQThX5vDaj21MiNXX4yHzMShdzKWAEqqTltIJjxr+oO/e4oqYpKWlKuH+xSBxECQHa89i3H5qZMz9loyhabqLD227YQfcls7lCTbuRHwHuQF+IwnAk2D5uBm27PjIcqjhI9ivZYQGuCG6aZOn/tvhU=",
            //同步跳转
            'return_url' => 'https://example.com/example/return_url.php',
            //异步通知地址
            'notify_url' => 'https://example.com/example/notify_url.php',
            //云联惠API网关
            'gatewayUrl' => "https://openapi.yunlianhui.com",   //开发：openapidev  正式：openapi
            //云联惠开放平台收银台
            'gatewayPay' => "https://openpay.yunlianhui.com", //开发：openpaydev  正式：openpay
            //云联惠公钥,查看地址：https://docs.yunlianhui.com/keyManage
            'alipay_public_key' => "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDeEmjFIhn+HwFSpCK+taWeU1qzHxotUPFyrnjz5c6Or8SntgIYUuGVl8VYkGkKWUz8FUr1vNNd/NPRNSOh8wTJiy7H//dOzhSkDp6c+CrS87qeqX+Fmj0a5g4y/Z6FDD0UpgoD6qrONbxy4vKWgy8c2XGCKt6l6V/CmyZcdd7eHQIDAQAB",

        ];
        $oauth_client = new OAuth2($config['gatewayUrl'], $config['client_id'], $config['client_secret'], $config['client_private_key'], $config['redirect_uri']);


        try {
            $result = $oauth_client->sendAnResourceRequest([
                'client_id' => $config['client_id'],
                'access_token' => $user_token,
                'timestamp' => (string)time(),
            ], 'api/v2/getUserInfo');
            echo "获取成功<br />member_id：" . $result['member_id']
                . "<br />member_class：" . $result['member_class']
                . "<br />member_type：" . $result['member_type']
                . "<br />mobile：" . $result['mobile']
                . "<br />rcm_id：" . $result['rcm_id']
                . "<br />email：" . $result['email'];
        } catch (\YunLianHui\ApiException $exception) {
            print_r('接口请求失败<br> ' . '错误信息是:' . $exception->getMessage());
        }
        return $result;
    }

    /**
     * 更新用户云联惠信息
     * @param $phone
     * @param $token
     * @param $member_id
     */
    public static function updateYlhUserInfo($phone, $token, $member_id)
    {
        $cmd = \Yii::$app->db->createCommand('update t_merchant set ylh_token=:token,ylh_id=:member_id,ylh_mobile=:phone ');
        $cmd->bindValue(':token', $token);
        $cmd->bindValue(':member_id', $member_id);
        $cmd->bindValue(':phone', $phone);
//                 var_dump($cmd->rawSql);
        DbCacheUtility::execute($cmd);
    }


    public static function test()
    {
        $trade_no = Tools::db_uuid();
        $mobile = '13802240011';
        $amount = 1000;

        $config = [
            //应用ID
            'client_id' => 'WYFX',
            //应用密钥
            'client_secret' => 'WYFX',
            //应用回调地址
            'redirect_uri' => 'http://119.23.110.230/oauth/callback',
            //应用私钥，您的原始格式RSA私钥
            'client_private_key' => "MIICXAIBAAKBgQDeEmjFIhn+HwFSpCK+taWeU1qzHxotUPFyrnjz5c6Or8SntgIYUuGVl8VYkGkKWUz8FUr1vNNd/NPRNSOh8wTJiy7H//dOzhSkDp6c+CrS87qeqX+Fmj0a5g4y/Z6FDD0UpgoD6qrONbxy4vKWgy8c2XGCKt6l6V/CmyZcdd7eHQIDAQABAoGBAKITP4H41I2iZV3CS1Vyz3BRF5Y5cep28/EmI0Kmi22aHOXmMXs9KkT6ot5zbyZNbKFijPXynTUwbAt5RAtTiT6O5yuC/dfLoo1oXuw66YCirZsYVgeghnXnHFdzNi/pWponW6Lc+TtTsB85F94Pcz8RuIemlN0EwpysdkYTHZfhAkEA9sJ8wyQQy1kWVkMFSiac56towxZGZ9sx+Q6a8Vd6blJZOpD25hE/wPR6Xq/xq8nlGNSehf19Xoac2XGHpYNPVQJBAOZjQdf6QAKERU47qH9G/h8JdUqipNDNFF8nWM8cAmHfmiq9SNof22ek/UolWcJkTL5qTcby4E+4J4MEP9g7g6kCQAbPrYPxbek/B0fQR8gZMsGOULD5322kdkeqqIo64O1EpqPgNoB5P2pDFVGhx6j3RLSfwdRu/9PpIVE7OgROkJUCQHQu9hOO9hzOy4yqdUzKZnkMcgQThX5vDaj21MiNXX4yHzMShdzKWAEqqTltIJjxr+oO/e4oqYpKWlKuH+xSBxECQHa89i3H5qZMz9loyhabqLD227YQfcls7lCTbuRHwHuQF+IwnAk2D5uBm27PjIcqjhI9ivZYQGuCG6aZOn/tvhU=",
            //同步跳转
            'return_url' => 'https://example.com/example/return_url.php',
            //异步通知地址
            'notify_url' => 'https://example.com/example/notify_url.php',
            //云联惠API网关
            'gatewayUrl' => "https://openapidev.yunlianhui.com",   //开发：openapidev  正式：openapi
            //云联惠开放平台收银台
            'gatewayPay' => "https://openpaydev.yunlianhui.com", //开发：openpaydev  正式：openpay
            //云联惠公钥,查看地址：https://docs.yunlianhui.com/keyManage
            'alipay_public_key' => "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDeEmjFIhn+HwFSpCK+taWeU1qzHxotUPFyrnjz5c6Or8SntgIYUuGVl8VYkGkKWUz8FUr1vNNd/NPRNSOh8wTJiy7H//dOzhSkDp6c+CrS87qeqX+Fmj0a5g4y/Z6FDD0UpgoD6qrONbxy4vKWgy8c2XGCKt6l6V/CmyZcdd7eHQIDAQAB",

        ];
        $oauth_client = new OAuth2($config['gatewayUrl'], $config['client_id'], $config['client_secret'], $config['client_private_key'], $config['redirect_uri']);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $trade_no;
        //订单名称，必填
        $subject = '屏主广告';
        //付款金额，必填
        $total_amount = $amount;
        //商品描述，必填
        $body = '屏主广告';
        //买家手机号
        $buyer_mobile = $mobile;
        $token = '1b0a43e68cc4fc332b529325aab1db73c9b3d9e1';
        $oauth_client = new OAuth2($config['gatewayUrl'], $config['client_id'], $config['client_secret'], $config['client_private_key'], $config['redirect_uri']);
        try {
            $result = $oauth_client->sendAnResourceRequest([
                'client_id' => $config['client_id'],
                'access_token' => $token,
                'timestamp' => (string)time(),
                'buyer_mobile' => $buyer_mobile,
                'out_trade_no' => $out_trade_no,
                'subject' => $subject,
                'body' => $body,
                'total_amount' => $total_amount,
            ], 'api/v2/returnPoints');
            $flag = $result['first_time'] ? '第一次' : '已注册';
            echo "全返成功<br />订单号：" . $result['order_id'] . "<br />订单状态：" . $result['order_status']
                . "<br />会员状态：" . $flag;
            self::saveYLHPointSendRecord($mobile, $out_trade_no, $amount, '', $result['order_id'], $result['order_status']);
        } catch (\YunLianHui\ApiException $exception) {
            print_r('接口请求失败<br> ' . '错误信息是:' . $exception->getMessage());
        }
    }


}